import pymysql
from DBUtils.PooledDB import PooledDB
from scrapy.conf import settings

class PTConnectionPool(object):
    __pool = None;
    def __enter__(self):
        self.conn = self.getConn();
        self.cursor = self.conn.cursor();
        return self;

    def getConn(self):
        if self.__pool is None:
            self.__pool = PooledDB(creator=pymysql, mincached=settings['DB_MIN_CACHED'] , maxcached=settings['DB_MAX_CACHED'],
                                   maxshared=settings['DB_MAX_SHARED'], maxconnections=settings['DB_MAX_CONNECYIONS'],
                                   blocking=settings['DB_BLOCKING'], maxusage=settings['DB_MAX_USAGE'],
                                   setsession=settings['DB_SET_SESSION'],
                                   host=settings['DB_TEST_HOST'] , port=settings['DB_TEST_PORT'] ,
                                   user=settings['DB_TEST_USER'] , passwd=settings['DB_TEST_PASSWORD'] ,
                                   db=settings['DB_TEST_DBNAME'] , use_unicode=False, charset=settings['DB_CHARSET']);

        return self.__pool.connection()

    """
    @summary: 释放连接池资源
    """
    def __exit__(self, type, value, trace):
        self.cursor.close()
        self.conn.close()

'''
@功能：获取PT数据库连接
'''
def getPTConnection():

    return PTConnectionPool();